<template>
  <view>
    <view class="vocab-test-container">
      <!-- 测试卡片 -->
      <view class="test-card">
        <!-- 顶部进度与返回 -->
        <view class="test-header">
          <!-- 返回按钮：u-button 替换原生按钮 -->
          <i class="fa-solid fa-circle-left" @click="goBack"/>

          <view class="progress-container">
            <view class="progress-text">第 {{ currentQuestionIndex + 1 }} / {{ totalQuestions }} 题</view>
            <!-- 进度条：u-progress 替换原生进度条 -->
            <!--            <u-progress
                            :percent="progressPercentage"
                            height="6"
                            activeColor="#3B82F6"
                            bgColor="#F3F4F6"
                            radius="3"
                        ></u-progress>-->
          </view>
        </view>

        <!-- 题目内容区域 -->
        <view class="question-container">
          <view class="question-word">{{ currentQuestion.word }}</view>
          <view class="question-prompt">请选择最符合的释义：</view>

          <!-- 选项列表 -->
          <view class="options-list">
            <!-- 选项按钮：u-button 替换原生按钮 -->
            <u-button
                v-for="(option, index) in currentQuestion.options"
                :key="index"
                class="option-btn"
                :class="{
              'option-selected': selectedOption === index,
              'option-correct': isProcessing && index === currentQuestion.correctAnswer,
              'option-incorrect': isProcessing && selectedOption === index && selectedOption !== currentQuestion.correctAnswer,
              'option-highlight': isProcessing
            }"
                :disabled="isProcessing || hasSelected"
                @click="selectOption(index)"
                plain
                shape="radius"
            >
              {{ option }}
            </u-button>

            <!-- 不认识按钮 -->
            <u-button
                class="dont-know-btn"
                :class="{
              'btn-active': selectedAsUnknown,
              'option-incorrect': isProcessing && selectedAsUnknown,
              'option-highlight': isProcessing
            }"
                :disabled="isProcessing || hasSelected"
                @click="markAsUnknown"
                plain
                shape="radius"
            >
              <view style="display: flex;gap: 3px">
                <view class="icon-unknown">?</view>
                <text class="unknown-text">不认识</text>
              </view>
            </u-button>

            <!-- 测试数据状态栏 -->
            <view class="test-stats-bar">
              <view class="stat-item correct">
                <u-icon name="checkmark" color="#059669" size="14"></u-icon>
                <text class="stat-label">正确</text>
                <text class="stat-value">{{ rightAnswerCount }}</text>
              </view>
              <view class="stat-item wrong">
                <u-icon name="close" color="#DC2626" size="14"></u-icon>
                <text class="stat-label">错误</text>
                <text class="stat-value">{{ wrongAnswerCount }}</text>
              </view>
              <view class="stat-item guess">
                <u-icon name="question" color="#F59E0B" size="14"></u-icon>
                <text class="stat-label">猜测</text>
                <text class="stat-value">{{ guessWord }}</text>
              </view>
              <view class="stat-item error-streak">
                <u-icon name="arrow-down" color="#9333EA" size="14"></u-icon>
                <text class="stat-label">连错</text>
                <text class="stat-value">{{ continuousErrorCount }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 策略调整提示弹窗：u-toast 替换自定义弹窗 -->
      <u-toast ref="showingStrategyTipToast"></u-toast>
    </view>

    <!-- 退出确认弹窗：u-modal 替换原生 confirm -->
    <u-modal
        :show="showQuitModal"
        title="提示"
        content="是否退出测试？"
        :show-confirm-button="true"
        :show-cancel-button="true"
        confirm-text="确定"
        cancel-text="取消"
        @confirm="handleQuitConfirm"
        @cancel="showQuitModal = false"
    ></u-modal>

    <!-- 猜测提示弹窗：u-modal 替换原生 msgbox -->
    <u-modal
        :show="showGuessWarnModal"
        title="提示"
        content="为确保测试结果准确性，不认识的单词请直接选择不认识！"
        :show-confirm-button="true"
        :show-cancel-button="false"
        confirm-text="确定"
        @confirm="showGuessWarnModal = false"
    ></u-modal>
  </view>
</template>


<script>
import {endVocalTest, question} from '@/api/vocabTest'
import AudioCacheUtil from "../../utils/AudioCacheUtil";

export default {
  name: 'VocabTestStart',
  data() {
    return {
      rightAnswerCount: 0, // 正确数
      wrongAnswerCount: 0, // 错误数
      continuousErrorCount: 0, // 连错数
      continuousRightCount: 0, // 连对数
      guessWord: 0, // 猜测数
      currentQuestionIndex: 0,
      totalQuestions: 0,
      selectedOption: null,
      selectedAsUnknown: false,
      isProcessing: false, // 答案处理中
      tipType: 'down', // 提示类型：down（降级）、up（升级）
      tipTitle: '', // 提示标题
      tipDesc: '', // 提示描述
      questions: [],
      showQuitModal: false, // 退出确认弹窗
      showGuessWarnModal: false, // 猜测提示弹窗
      audioContext: null // UniApp 音频上下文
    }
  },
  computed: {
    currentQuestion() {
      const currentQ = this.questions[this.currentQuestionIndex] || {}
      // 题目切换时播放音频（避免重复触发）
      setTimeout(() => {
        if (currentQ.word && !this.isProcessing) {
          AudioCacheUtil.play(currentQ.word, 'en')
        }
      }, 200)
      return currentQ
    },
    progressPercentage() {
      return this.totalQuestions ? Math.round(((this.currentQuestionIndex + 1) / this.totalQuestions) * 100) : 0
    },
    hasSelected() {
      return this.selectedOption !== null || this.selectedAsUnknown
    }
  },
  mounted() {
    // 请求题目数据
    this.reqData()
  },
  methods: {
    // 请求题目数据
    async reqData() {
      try {
        const res = await question({
          rightNum: this.rightAnswerCount,
          wrongNum: this.wrongAnswerCount,
          guessNum: this.guessWord,
          continueWrongNum: this.continuousErrorCount
        })
        this.questions = res || []

        // 测试结束：跳转结果页（UniApp 路由）
        if (this.questions.length === 1 && this.questions[0].vocalTestLevel) {
          console.log('测试结束')
          uni.navigateTo({
            url: `/pages/components/VocabTestResult?vocalTestLevel=${this.questions[0].vocalTestLevel}&vocalTestWordNumber=${this.questions[0].vocalTestWordNumber}`
          })
          console.log('页面跳转结束')
          return
        }

        // 统一正确答案为数字类型
        this.questions.forEach(item => {
          item.correctAnswer = Number(item.correctAnswer)
        })
        this.totalQuestions = this.questions.length
      } catch (err) {
        uni.showToast({title: '题目加载失败', icon: 'none'})
        console.error('题目请求错误：', err)
      }
    },

    // 刷新题库（降级/升级后）
    async refresh() {
      // 重新请求题库
      this.questions = []
      this.currentQuestionIndex = 0
      await this.reqData()
      // 重置统计数据
      this.rightAnswerCount = 0
      this.wrongAnswerCount = 0
      this.continuousErrorCount = 0
      this.guessWord = 0
    },

    // 显示策略调整提示（u-toast 控制）
    showStrategyTip(type, title, desc) {
      this.tipType = type
      this.tipTitle = title
      this.tipDesc = desc
      this.isProcessing = false

      this.$refs.showingStrategyTipToast.show({
        type: type === 'down' ? 'error' : 'success',
        icon: false,
        title: title,
        message: desc,
      });
    },

    // 打开退出确认弹窗
    goBack() {
      if (this.isProcessing) return
      this.showQuitModal = true
    },

    // 确认退出测试
    handleQuitConfirm() {
      endVocalTest()
      // 返回上一页（UniApp 路由）
      uni.navigateTo({url: '/pages/system-frame'})
    },

    // 选择选项
    selectOption(index) {
      if (this.isProcessing) return

      const isCorrect = index === this.currentQuestion.correctAnswer
      if (isCorrect) {
        // 答对逻辑
        this.rightAnswerCount++
        this.continuousErrorCount = 0
        this.continuousRightCount++

        // 计算正确率，判断是否升级
        let rightRadio = this.rightAnswerCount / this.questions.length
        if (this.continuousRightCount >= 6) {
          rightRadio = this.rightAnswerCount / (this.rightAnswerCount + this.wrongAnswerCount)
          if (rightRadio >= 0.8) {
            rightRadio = 0.85
            this.continuousRightCount = 0
            this.rightAnswerCount = Math.floor(this.questions.length * 0.85)
          }
        }

        // 触发升级
        if (rightRadio >= 0.85) {
          this.showStrategyTip(
              'up',
              '测试难度升级',
              '恭喜！你已连续答对多题，即将为你提升题目难度'
          )
          setTimeout(() => this.refresh(), 1000)
          return
        }
      } else {
        // 答错逻辑
        this.guessWord++
        this.wrongAnswerCount++
        this.continuousErrorCount++
        this.continuousRightCount = 0

        // 触发降级
        const errorRadio = this.wrongAnswerCount / this.questions.length
        if (this.continuousErrorCount >= 3 || errorRadio >= 0.15) {
          this.showStrategyTip(
              'down',
              '策略更新',
              '更换匹配难度！'
          )
          setTimeout(() => this.refresh(), 1000)
          return
        }

        // 首次猜测提示
        if (this.guessWord === 1) {
          // 播放警告音频（UniApp 音频）
          const warnAudio = uni.createInnerAudioContext()
          warnAudio.src = '/static/vocal-test-waring.mp3'
          warnAudio.play()
          // 显示提示弹窗
          this.showGuessWarnModal = true
        }
      }

      this.selectedOption = index
      this.selectedAsUnknown = false
      this.processAnswer()
    },

    // 标记为“不认识”
    markAsUnknown() {
      if (this.isProcessing) return

      this.wrongAnswerCount++
      this.continuousErrorCount++

      // 触发降级
      if (this.continuousErrorCount > 2) {
        this.showStrategyTip(
            'down',
            '测试难度调整',
            '已连续多题选择“不认识”，即将为你降低题目难度'
        )
        setTimeout(() => this.refresh(), 1000)
        return
      }

      this.selectedAsUnknown = true
      this.selectedOption = null
      this.processAnswer()
    },

    // 处理答案（展示反馈后切换题目）
    processAnswer() {
      this.isProcessing = true

      // 1秒后切换题目
      setTimeout(() => {
        if (this.currentQuestionIndex < this.questions.length - 1) {
          this.currentQuestionIndex++
          this.resetSelection()
        } else {
          // 最后一题：跳转结果页
          uni.navigateTo({url: '/pages/vocab-test/result'})
        }
      }, 1000)
    },

    // 重置选择状态
    resetSelection() {
      this.selectedOption = null
      this.selectedAsUnknown = false
      this.isProcessing = false
    }
  }
}
</script>


<style scoped lang="scss">
* {
  user-select: none;
}


/* 基础容器样式 */
.vocab-test-container {
  min-height: 100vh;
  max-height: 100vh;
  display: flex;
  justify-content: center;
  padding: 20rpx;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #E6F0FF 0%, #FFFFFF 100%);
  z-index: 1;
}

/* 测试卡片 */
.test-card {
  width: 100%;
  max-width: 550px;
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.08);
  padding: 25rpx clamp(15rpx, 8vw, 30rpx);
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 头部进度区域 */
.test-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

/* 进度容器 */
.progress-container {
  flex: 1;
}

.progress-text {
  font-size: 28rpx;
  color: #6B7280;
  margin-bottom: 8rpx;
  text-align: right;
}

/* 题目内容区域 */
.question-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.question-word {
  font-size: 56rpx;
  font-weight: 700;
  color: #1F2937;
  margin-bottom: 20rpx;
  font-family: 'Poppins', 'Inter', sans-serif;
}

.question-prompt {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #F3F4F6;
}

/* 选项列表 */
.options-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  margin-bottom: 20rpx;
  flex: 1;
  overflow-y: auto;
  padding-bottom: 20rpx;
}

/* 选项按钮：覆盖 u-button 样式 */
.option-btn {
  width: 100% !important;
  padding: 24rpx 28rpx !important;
  background: #F9FAFB !important;
  border: 1px solid #E5E7EB !important;
  border-radius: 12rpx !important;
  text-align: left !important;
  font-size: 32rpx !important;
  color: #1F2937 !important;
  margin: 0 !important;
  height: auto !important;

  &::v-deep .u-button__content {
    justify-content: flex-start !important;
    padding: 0 !important;
  }

  &:hover:not(:disabled) {
    background: #F3F4F6 !important;
    border-color: #D1D5DB !important;
  }
}

.option-selected {
  background: #EFF6FF !important;
  border-color: #93C5FD !important;
  color: #1E40AF !important;
  font-weight: 500 !important;
}

/* 答案反馈样式 */
.option-correct {
  background: #ECFDF5 !important;
  border-color: #A7F3D0 !important;
  color: #059669 !important;
  font-weight: 500 !important;
}

.option-incorrect {
  background: #FEF2F2 !important;
  border-color: #FECACA !important;
  color: #DC2626 !important;
  font-weight: 500 !important;
}

/* 膨胀动画效果 */
.option-highlight {
  animation: pulse 0.5s ease-in-out;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.03);
  }
  100% {
    transform: scale(1);
  }
}

/* 不认识按钮：覆盖 u-button 样式 */
.dont-know-btn {
  width: 100% !important;
  padding: 24rpx 28rpx !important;
  background: #FEF3F2 !important;
  border: 1px solid #FEE2E2 !important;
  border-radius: 12rpx !important;
  text-align: left !important;
  font-size: 32rpx !important;
  color: #DC2626 !important;
  margin: 0 !important;
  height: auto !important;
  display: flex !important;
  align-items: center !important;
  gap: 10rpx !important;

  &::v-deep .u-button__content {
    display: flex !important;
    align-items: center !important;
    gap: 10rpx !important;
    padding: 0 !important;
  }

  &:hover:not(:disabled) {
    background: #FEE2E2 !important;
  }
}

.dont-know-btn.btn-active {
  background: #FEE2E2 !important;
  border-color: #FCA5A5 !important;
  font-weight: 500 !important;
}

.icon-unknown {
  width: 36rpx;
  height: 36rpx;
  background: #EF4444;
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 36rpx;
  font-weight: bold;
  font-size: 24rpx;
}

.unknown-text {
  flex: 1;
}

/* 测试数据状态栏 */
.test-stats-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 16rpx;
  background: #F9FAFB;
  border-radius: 8rpx;
  margin-top: 20rpx;
  font-size: 24rpx;
}

/* 单个数据项 */
.stat-item {
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.stat-item i {
  font-size: 28rpx;
  width: 32rpx;
  text-align: center;
}

.stat-label {
  color: #6B7280;
}

.stat-value {
  font-weight: 600;
  min-width: 32rpx;
  text-align: center;
}

/* 不同状态色彩 */
.stat-item.correct {
  & text.stat-value {
    color: #059669;
  }
}

.stat-item.wrong {
  & text.stat-value {
    color: #DC2626;
  }
}

.stat-item.guess {
  & text.stat-value {
    color: #F59E0B;
  }
}

.stat-item.error-streak {
  & text.stat-value {
    color: #9333EA;
  }
}

/* 响应式调整（小屏幕换行） */
@media (max-width: 375px) {
  .test-stats-bar {
    flex-wrap: wrap;
    gap: 10rpx;
    padding: 15rpx 16rpx;
  }

  .stat-item {
    flex: 1;
    justify-content: center;
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .test-card {
    max-height: none;
    height: 100%;
  }

  .question-word {
    font-size: 48rpx;
  }

  .option-btn, .dont-know-btn {
    padding: 20rpx 24rpx !important;
    font-size: 30rpx !important;
  }
}

/* 修复 uView 组件样式穿透 */
::v-deep .u-toast__content {
  max-width: 80% !important;
  text-align: left !important;
  padding: 20rpx 24rpx !important;
  border-radius: 12rpx !important;
}

::v-deep .u-toast__icon {
  margin-right: 15rpx !important;
}

::v-deep .u-modal {
  max-width: 500rpx !important;
  border-radius: 16rpx !important;
}

::v-deep .u-progress__bar {
  border-radius: 3rpx !important;
}
</style>
